//
//  ImageDownloader.m
//  hudong
//
//  Created by simon on 10-8-30.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ImageDownloader.h"
//#import "CacheManager.h"

@implementation ImageDownloader
@synthesize  tag,imageReceiver,imageURLString,imageConnection;

-(id)init{
    self = [super init];
	if(self){
		imageData = [[NSMutableData alloc] init];
	}
	return self;
}

-(void)startDownloadWithImageURLString:(NSString*)urlString{
	self.imageURLString = urlString;
	
	NSURL* url = [[NSURL alloc] initWithString:urlString];
	NSURLRequest* request = [NSURLRequest requestWithURL:url];
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	self.imageConnection = connection;
	[url release];
	[connection release];
	
}

- (void)cancelDownload{
	[self.imageConnection cancel];
	self.imageConnection = nil;
	imageData = nil;
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
	NSLog(@"%s   %d",__FUNCTION__,__LINE__);
	[imageData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	NSLog(@"%s   %d",__FUNCTION__,__LINE__);
	if(imageReceiver != nil){
		UIImage* image = [[UIImage alloc] initWithData:imageData];
		[imageReceiver imageDownloader:self didReceiveImage:image];
		[image release];
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	NSLog(@"download error : %@",[error description]);
	self.imageConnection = nil;
	imageData = nil;
}

- (void)dealloc{
	[imageData release];
	[imageURLString release];
	[imageConnection cancel];
	[imageConnection release];
	[super dealloc];

}

@end
